package crm.salesOrderProcessing.managedbean;

import commonInfrastructure.accountManagement.entity.SalesmanEntity;
import commonInfrastructure.accountManagement.session.SalesmanSessionBean;
import crm.clientManagement.entity.CompanyEntity;
import javax.faces.event.ActionEvent;
import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.servlet.http.HttpServletRequest;
import mrp.productionPlanning.session.MRPATPSessionBean;
import crm.salesOrderProcessing.entity.LineItemEntity;
import crm.salesOrderProcessing.entity.SalesQuotationEntity;
import crm.salesOrderProcessing.session.PriceManagementSessionBean;
import crm.salesOrderProcessing.session.SalesQuotationSessionBean;
import crm.salesOrderProcessing.util.exception.SalesException;

@ManagedBean
@ViewScoped
public class QuotationForConfirmManagedBean implements Serializable {

    @EJB
    MRPATPSessionBean mrpATPSessionBean;
    @EJB
    PriceManagementSessionBean priceManageSessionBean;
    @EJB
    SalesQuotationSessionBean salesQuotationSessionBean;
    @EJB 
    SalesmanSessionBean salesmanManager;
    
    private List<LineItemEntity> lineItemList;
    private double userDiscount = 0.00;
    private double totalPrice,tempPrice;
    private CompanyEntity selectedCompany;
    private SalesQuotationEntity salesQuotation;
    private Date validUntil;
    private SalesmanEntity salesman;
    private int leadTime;

    public QuotationForConfirmManagedBean() {
        
    }
    
    public void initView(PhaseEvent event) throws ParseException {
        if (salesQuotation == null) {
            salesQuotation = (SalesQuotationEntity) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("quotation");
        }
        lineItemList = salesQuotation.getQuotationLineItems();
        selectedCompany = salesQuotation.getCompany();
        salesQuotation.setValidUntil(getvu());
        validUntil=salesQuotation.getValidUntil();
        leadTime = salesQuotation.getLeadTime();
   }

    public void saveNewQuotation(ActionEvent event) throws IOException, ParseException,SalesException {
//        validUntil= (Date)event.getComponent().getAttributes().get("validUntil"); 
        totalPrice=getTempPrice();
        SalesQuotationEntity salesQuotation = salesQuotationSessionBean.addNewSalesQuotation(selectedCompany,lineItemList,validUntil, totalPrice, userDiscount,leadTime);

        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("newQuotation", salesQuotation);
        FacesContext.getCurrentInstance().getExternalContext().redirect("createSaleQuotationResult.xhtml");
    }

    public List<LineItemEntity> getLineItemList() {
        return lineItemList;
    }

    public void setLineItemList(List<LineItemEntity> lineItemObj) {
        this.lineItemList = lineItemObj;
    }
   
    public void checkLimit(ActionEvent event) throws IOException{
        if(userDiscount!=0.0){
        
         HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
         Long salesmanId = (Long) request.getSession().getAttribute("userId");
        
         salesman= salesmanManager.getSalesmanById(salesmanId);
         if((1.0-userDiscount)<salesman.getDiscountLimit()){//exceed salesman discount limit
              userDiscount=0.0;   
             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Exceed Discount Limit.", ""));        
                 
         }
       }
    }
    
    public double returnTotalPrice() {
        totalPrice = 0.0;
        
        for (int i = 0; i < getLineItemList().size(); i++) { //for each lineItem, return a after-discount price+ lead time
            totalPrice = totalPrice + getLineItemList().get(i).getPrice() * getLineItemList().get(i).getQuantity();
        }
        if (userDiscount == 0.0) {
             setTempPrice(roundTwoDecimals(totalPrice));
        }else{ 
            setTempPrice(roundTwoDecimals(totalPrice * roundTwoDecimals(1.0-userDiscount)));
            }
         return getTempPrice();
    }
    
    public Date getvu() throws ParseException {
       
//      String dateString = "18-10-2011"; 
//      SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); 
//    Date convertedDate = dateFormat.parse(dateString); 
   // TDY:  the code below should give u 15 days from now.
    Calendar daysLater = Calendar.getInstance();
        daysLater.add(Calendar.DAY_OF_MONTH, 15);
        Date convertedDate = daysLater.getTime();
      return convertedDate;
    //  DateFormat formatter ; 
     // Date date ; 
     // formatter = new SimpleDateFormat("dd-mm-yyyy");
      //date = (Date)formatter.parse(str_date);  
     // return date; 
//   Calendar cal = Calendar.getInstance();   
//   int maxDay=cal.getActualMaximum(Calendar.DAY_OF_MONTH);   
//   java.text.Format formatter3=new java.text.SimpleDateFormat("yyyy-MM-"+maxDay);   
//  return formatter3.format(cal.getTime());    
    }


    public double getTotalPrice() {
        return this.roundTwoDecimals(totalPrice);
    }

    public CompanyEntity getSelectedCompany() {
        return this.selectedCompany;
    }

    public void setSelectedCompany(CompanyEntity company) {
        this.selectedCompany = company;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }
    
    public Date getValidUntil(){
        return this.validUntil;
    }
    public void setValidUntil(Date vd){
        this.validUntil=vd;
    }

    public double getUserDiscount() {
        return this.userDiscount;
    }

    public void setUserDiscount(double ud) {
        this.userDiscount = ud;
    }

    private double roundTwoDecimals(double d) {
        DecimalFormat twoDForm = new DecimalFormat("#.##");
        return Double.valueOf(twoDForm.format(d));
    }

    public double getTempPrice() {
        return tempPrice;
    }

    public void setTempPrice(double tempPrice) {
        this.tempPrice = tempPrice;
    }

    /**
     * @return the leadTime
     */
    public int getLeadTime() {
        return leadTime;
    }

    /**
     * @param leadTime the leadTime to set
     */
    public void setLeadTime(int leadTime) {
        this.leadTime = leadTime;
    }
}
